import { Component, OnInit } from '@angular/core';
import {FormObjModel} from '../formObj.model';
import {RequestForServiceService} from '../request-for-service.service';
import {ActivatedRoute, Router} from '@angular/router';
import {Message, TreeNode} from 'primeng/primeng';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {PublicService} from '../../services/public.service';
import {PUblicMethod} from '../../services/PUblicMethod';
import {EventBusService} from '../../services/event-bus.service';
import {timeValidator} from '../../validator/validators';

@Component({
  selector: 'app-solve-service',
  templateUrl: './solve-service.component.html',
  styleUrls: ['./solve-service.component.scss']
})
export class SolveServiceComponent implements OnInit {

    formObj: FormObjModel;
    display: boolean = false;
    filesTree4: TreeNode[] = [];
    selected: Array<any> = [];
    options: Object = {
        'departments': []
    };
    message: Message[] = [];               // 交互提示弹出框
    myForm: FormGroup;
    zh: any;
    maxDate: Date;
    minDate: Date;

    constructor(private rfsService: RequestForServiceService,
                private activatedRouter: ActivatedRoute,
                private router: Router,
                private fb: FormBuilder,
                private eventBusService: EventBusService,
                private publicService: PublicService) { }

    ngOnInit() {
        this.zh = new PUblicMethod().initZh();
        this.formObj = new FormObjModel();
        this.createForm();
        this.formObj.sid = this.activatedRouter.snapshot.paramMap.get('id');
        this.initForm();
        this.formObj.status = this.activatedRouter.snapshot.paramMap.get('status');
        this.getFlowChart();
        this.maxDate = new Date();
    }
    getFlowChart() {
        this.rfsService.getFlowChart(this.formObj.status).subscribe(res => {
            this.eventBusService.rfs.next(res);
        });
    }
    goBack() {
        this.router.navigate(['../serviceOverview'], {relativeTo: this.activatedRouter});
    }
    initForm() {
        this.rfsService.getTrick(this.formObj.sid).subscribe(res => {
           this.formObj.process_time = res['process_time'];
           this.minDate = new Date(Date.parse(res['process_time']));
           // this.formObj.finish_time = res['finish_time'];
           this.formObj.acceptor_org = res['acceptor_org'];
           this.formObj.acceptor = res['acceptor'];
           this.formObj.acceptor_pid = res['acceptor_pid'];
           this.formObj.acceptor_org_oid = res['acceptor_org_oid']
           this.formObj.reason = res['reason'];
           this.formObj.means = res['means'];
           this.formObj.finish_time = PUblicMethod.formateEnrtyTime(new Date());
        });
    }
    createForm() {
        this.myForm = this.fb.group({
            'finish_time': '',
            'solve_org': '',
            'means': '',
            'timeGroup': this.fb.group({
                'startTime': '',
                'endTime': ''
            }, {validator: timeValidator})
        });
    }
    showTreeDialog() {
        this.display = true;
        this.publicService.getDepartmentDatas().subscribe(res => {
            this.filesTree4 = res;
        });
    }
    clearTreeDialog() {
        this.formObj.acceptor = '';
        this.formObj.acceptor_org = '';
        this.formObj.acceptor_org_oid = '';
        this.formObj.acceptor_pid = '';
        this.options['departments'] = [];
        this.setValidators();
    }
    nodeExpand(event) {
        if (event.node) {
            this.publicService.getDepartmentDatas(event.node.oid, event.node.dep).subscribe(res => {
                event.node.children  = res;
            });
        }
    }
    closeTreeDialog() {
        this.display = false;
        this.formObj.solve_org = this.selected['label'];
        this.formObj.submitter_org_oid = this.selected['oid'];
        this.getDepPerson(this.selected['oid']);
    }
    getDepPerson(oid?) {
        this.publicService.getApprovers(oid).subscribe(res => {
            if (!res) {
                this.options['departments'] = [];
            }else {
                this.options['departments'] = res;
                this.formObj.solve_per_pid = res[0]['pid'];
                this.formObj.solve_per = res[0]['name'];
            }
        });
    }
    setValidators() {
        this.myForm.controls['solve_org'].setValidators([Validators.required]);
        this.myForm.controls['solve_org'].updateValueAndValidity();
        this.myForm.get(['timeGroup', 'endTime']).setValidators([Validators.required]);
        // this.myForm.controls['finish_time'].setValidators([Validators.required]);
        // this.myForm.controls['finish_time'].updateValueAndValidity();
        this.myForm.get(['timeGroup', 'endTime']).updateValueAndValidity();
        this.myForm.controls['means'].setValidators([Validators.required]);
        this.myForm.controls['means'].updateValueAndValidity();
    }
    get department() {
        return this.myForm.controls['solve_org'].untouched && this.myForm.controls['solve_org'].hasError('required');
    }
    get finishTime() {
        // return this.myForm.controls['finish_time'].untouched && this.myForm.controls['finish_time'].hasError('required');
        return this.myForm.get(['timeGroup', 'endTime']).untouched && this.myForm.get(['timeGroup', 'endTime']).hasError('required');
    }
    get endTime() {
        let res = false;
        if (this.formObj.process_time && this.formObj.finish_time) {
            let processTime = new Date(this.formObj.process_time).getTime();
            let finishTime = new Date(this.formObj.finish_time).getTime();
            if (processTime > finishTime) {
                res = true;
               return res;
            }
        }
        return this.myForm.get(['timeGroup', 'endTime']).untouched && res;
    }
    get means() {
        return this.myForm.controls['means'].untouched && this.myForm.controls['means'].hasError('required');
    }
    showError() {
        this.message = [];
        this.message.push({severity: 'error', summary: '错误消息提示', detail: '请填写完整表单'});
    }
    resetFinishTime() {
        if (this.formObj.finish_time) {
            this.formObj.finish_time = PUblicMethod.formateEnrtyTime(this.formObj.finish_time);
            // console.warn(Date.parse(this.formObj.process_time));
        }
        // console.warn(this.formObj.occurrence_time);
    }
    save() {
        this.formObj.status = '处理中';
        this.resetFinishTime();
        this.rfsService.saveOrSolveTrick(this.formObj).subscribe(res => {
            if ( res === '00000' ) {
                this.message = [];
                this.message.push({severity: 'success', summary: '消息提示', detail: '保存成功'});
                window.setTimeout(() => {
                    // this.router.navigateByUrl('/index/reqForService/rfsBase/serviceOverview');
                    this.goBack();
                }, 1100);
            }else {
                this.message = [];
                this.message.push({severity: 'error', summary: '消息提示', detail: `保存失败${res}`});
            }
        });
    }
    submitTrick() {
        if ( !this.formObj.finish_time
            || !this.formObj.means
        ) {
            this.showError();
            this.setValidators();
        }else {
            this.resetFinishTime();
            this.submitPost(this.formObj);
        }
    }
    submitPost(paper) {
        this.formObj.status = '已解决';
        this.rfsService.saveOrSolveTrick( paper ).subscribe(res => {
            if ( res === '00000' ) {
                this.message = [];
                this.message.push({severity: 'success', summary: '消息提示', detail: '操作成功'});
                window.setTimeout(() => {
                    this.router.navigate(['/index/reqForService/rfsBase/colseService', {id: this.formObj.sid, status: this.formObj.status}]);
                    this.goBack();
                }, 1100);
            }else {
                this.message = [];
                this.message.push({severity: 'error', summary: '消息提示', detail: `操作失败${res}`});
            }
        });
    }
}
